//
//  IDPViewController.m
//  Pong
//
//  Created by iD Student on 7/10/13.
//  Copyright (c) 2013 jasonkurtzman. All rights reserved.
//

#import "IDPViewController.h"

@interface IDPViewController ()

@end

@implementation IDPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    /*NSURL *url = [[NSBundle mainBundle] URLForResource:@"background" withExtension:@"mp3"];
    NSError *error;
    backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if(error != nil)
    {
        NSLog(@"No backgrnd music found!");
    }else
    {
        [backgroundMusic prepareToPlay];
        [backgroundMusic play];
    }
    */
    
    paddle1Score = 0;
    paddle2Score = 0;
    maxBallSpeed = 40;
    maxBallXSpeed = 45;
    maxMaxBallSpeed = 60;
    maxMaxBallSpeed = 65;
    counter = 0;
    ball = [[IDPBall alloc] init];
    ballHard = [[IDPBallHard alloc] init];
    [pointsLabel setText:@"0:0"];
    [self.view addSubview:ball.image];
    lastScorer = 1;
    [self.view setMultipleTouchEnabled:YES];
}

-(IBAction)playTwoPlayerPressed:(id)sender
{
    [backgroundMusic play];
    isTwoPlayer = YES;
    play2PlayerButton.hidden = YES;
    computerEasyButton.hidden = YES;
    computerMediumButton.hidden = YES;
    computerHardButton.hidden = YES;
    [self resetBall];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.033 target:self selector:@selector(updateGame) userInfo:nil repeats:YES];
}

-(IBAction)playVsComputerMediumPressed:(id)sender
{
    isTwoPlayer = NO;
    [backgroundMusic play];
    velocity = 18;
    //velocity = 2;
    play2PlayerButton.hidden = YES;
    computerEasyButton.hidden = YES;
    computerMediumButton.hidden = YES;
    computerHardButton.hidden = YES;
    [self resetBall];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.033 target:self selector:@selector(updateGame) userInfo:nil repeats:YES];
}

-(IBAction)playVsComputerEasyPressed:(id)sender
{
    isTwoPlayer = NO;
    [backgroundMusic play];
    velocity = 12;
    //velocity = 1;
    play2PlayerButton.hidden = YES;
    computerEasyButton.hidden = YES;
    computerMediumButton.hidden = YES;
    computerHardButton.hidden = YES;
    [self resetBall];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.033 target:self selector:@selector(updateGame) userInfo:nil repeats:YES];
}

-(IBAction) playVsComputerHardPressed:(id)sender
{
    isTwoPlayer = NO;
    [backgroundMusic play];
    velocity = 28;
    //velocity = 3;
    play2PlayerButton.hidden = YES;
    computerEasyButton.hidden = YES;
    computerMediumButton.hidden = YES;
    computerHardButton.hidden = YES;
    [self resetBall];
    //survivivalTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.033 target:self selector:@selector(updateGame) userInfo:nil repeats:YES];
    
}

-(void) resetBall
{
    ball.image.center = CGPointMake(160, 240);
    
    ball.velocityX = 0;
    if(lastScorer == 1) // Bottom Player Score, make ball go up
    {
        ball.velocityY = -5;
    }else if(lastScorer == 2) //Top player score, make ball go down
    {
        ball.velocityY = 5;
    }
}

-(void)timer
{
    survivalTime++;
    NSString *survivalString = [NSString stringWithFormat:@"%d", survivalTime];
    [survivalLabel setText:survivalString];
}

-(void) updateGame
{
    [self moveBall];
    //NSLog(@"%f", ball.velocityY);
   // NSLog(@"%f", ball.velocityX);
    [self checkForGoal];
    if(!isTwoPlayer)
    {
        [self AI];
    }
    counter++;
    
    if(counter >= 300)
    {
        //if(maxBallXSpeed < maxMaxBallXSpeed)
        //{
            //maxBallSpeed += 3;
            //maxBallXSpeed += 3;
            ball.velocityY += 5;
            ball.velocityX += 5;
            counter = 0;
            NSLog(@"Max Ball Speed increased");
        //}else
        //{
            //NSLog(@"Limit Reached");
        //}
    }
}

-(void) AI
{
    //float velocity = 0;
    /*if(compDifficulty == 1)
    {
        //Easy
        float velocity = 1;
    }else if(compDifficulty == 2)
    {
        //Medium
        float velocity = 2;
    }else if(compDifficulty == 3)
    {
        //Hard
        float velocity = 3;
    }*/
    
    
    float oldCenter = paddle2.center.x;
    float newCenter = oldCenter;
    float ballCenter = ball.image.center.x;
    
    if(ballCenter < oldCenter)
    {
        //Ball is to the left of paddle
        //if(paddle2.image.size.width -  < 10)
        //{
        //    velocity = 0;
        //}else
        //{
            newCenter -= velocity;
            paddle2.center = CGPointMake(newCenter, paddle2.center.y);
        //}
    }else if(ballCenter > oldCenter)
    {
        //Ball is to the right of paddle
        newCenter += velocity;
        paddle2.center = CGPointMake(newCenter, paddle2.center.y);
    }
}

-(void) moveBall
{
    CGPoint oldCenter = ball.image.center;
    ball.image.center = CGPointMake(oldCenter.x + ball.velocityX, oldCenter.y + ball.velocityY);
    
    BOOL didBallHitPaddle = NO;
    if(CGRectIntersectsRect(paddle1.frame, ball.image.frame))
    {
       // CGRect ballFrame = ball.image.frame;
        //ball.image.center = CGPointMake(ball.image.center.x, ballFrame.origin.y - ballFrame.size.height / 16);
        ball.image.center = CGPointMake(ball.image.center.x, ball.image.center.y - 5);
        didBallHitPaddle = YES;
    }else if(CGRectIntersectsRect(paddle2.frame, ball.image.frame))
    {
        //CGRect ballFrame = ball.image.frame;
        //ball.image.center = CGPointMake(ball.image.center.x, ballFrame.origin.y + ballFrame.size.height + ballFrame.size.height / 16);
        ball.image.center = CGPointMake(ball.image.center.x, ball.image.center.y + 5);
        didBallHitPaddle = YES;
    }
    
    if(didBallHitPaddle)
    {
        ball.velocityY *= -1.2;
        if(ball.velocityX < 1)
        {
            //Randomize balls velocity x
            ball.velocityX = arc4random() % 40 - 20;
        }else
        {
            //Randomize velocity between -velocityX and velocity X
            ball.velocityX *= 1.2;
            ball.velocityX = arc4random() % (abs(ball.velocityX * 2) + 1) - ball.velocityX;
            //ball.velocityX = arc4random() % 6 - 3;
        }
    }
    
    if(CGRectIntersectsRect(ball.image.frame, leftWall.frame))
    {
        CGRect ballFrame = ball.image.frame;
        ball.image.center = CGPointMake(leftWall.frame.origin.x + leftWall.frame.size.width + ballFrame.size.width / 2, ball.image.center.y);
        ball.velocityX *= -1.2;
    }else if(CGRectIntersectsRect(ball.image.frame, rightWall.frame))
    {
        CGRect ballFrame = ball.image.frame;
        ball.image.center = CGPointMake(rightWall.frame.origin.x - ballFrame.size.width / 2, ball.image.center.y);
        ball.velocityX *= -1.2;
    }
    
    if(ball.velocityY > maxBallSpeed)
        ball.velocityY = maxBallSpeed;
    else if(ball.velocityY < -maxBallSpeed)
        ball.velocityY = -maxBallSpeed;
    if(ball.velocityX > maxBallXSpeed)
        ball.velocityX = arc4random() % 20 + 5;
    else if(ball.velocityX < -maxBallXSpeed)
        ball.velocityX = -1 * arc4random() % 20 + 5;
}

-(void) checkForGoal
{
    if(CGRectIntersectsRect(ball.image.frame, topGoal.frame))
    {
        //Bottom Player Scores
        paddle1Score++;
        if(paddle1Score == 10)
        {
            [self performSegueWithIdentifier:@"SEGUE_RESULT_WIN" sender:self];
        }
        lastScorer = 1;
        NSLog(@"Player 2 Scored");
        NSString *pointsString = [NSString stringWithFormat:@"%d:%d", paddle1Score, paddle2Score];
        [pointsLabel setText:pointsString];
        [self resetBall];
    }else if(CGRectIntersectsRect(ball.image.frame, bottomGoal.frame))
    {
        //Top Player Scored
        paddle2Score++;
        if(paddle2Score == 10)
        {
            [self performSegueWithIdentifier:@"SEGUE_RESULT_LOSE" sender:self];
        }
        lastScorer = 2;
        NSLog(@"Player 1 Scored");
        NSString *pointsString = [NSString stringWithFormat:@"%d:%d", paddle1Score, paddle2Score];
        [pointsLabel setText:pointsString];
        [self resetBall];
    }
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    for(UITouch *touch in touches)
    {
        CGPoint point = [touch locationInView:self.view];
        if(isTwoPlayer)
        {
            if(point.y > 240)
            {
                //NSLog(@"Paddle on bottom half");
                //Touch on bottom half of screen.
                paddle1.center = CGPointMake(point.x, paddle1.center.y);
            }else if (point.y < 240)
            {
                //NSLog(@"Paddle on top half");
                //Touch on top half of screen.
                paddle2.center = CGPointMake(point.x, paddle2.center.y);
            }
        }else if(!isTwoPlayer)
        {
            paddle1.center = CGPointMake(point.x, paddle1.center.y);
            //paddle1.center = CGPointMake(point.x, point.y);
            //paddle2.center = CGPointMake(ball.image.center.x, paddle2.center.y);
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
